#include "cbitdaemon.h"

#include "ctorrentmanager.h"
#include "cdownload.h"

#include <buola/io/curi.h>
#include <buola/algorithm/container.h>
#include <buola/dbus/cproxy.h>
#include <buola/io.h>

namespace buola { namespace bitdaemon {

CBitDaemon *gBitDaemon;

CBitDaemon::CBitDaemon()
{
    gBitDaemon=this;
    bbox::register_service(this,"/org/buola/bitdaemon");
    mTorrentManager.reset(new CTorrentManager);
}

CBitDaemon::~CBitDaemon()
{
}

void CBitDaemon::AddDownload(CDownload *pDownload)
{
    mDownloads.emplace(pDownload->UID(),pDownload);
}

void CBitDaemon::RemoveDownload(CDownload *pDownload)
{
    mDownloads.erase(pDownload->UID());
}

void CBitDaemon::OpenTorrent(const io::CURI &pURI,const io::CURI &pDestination)
{
    msg_info() << "opening torrent " << pURI << "into" << pDestination << "\n";
    mTorrentManager->AddTorrent(pURI,pDestination);
}

std::vector<uint64_t> CBitDaemon::GetDownloadList()
{
    std::vector<uint64_t> lRet;

    for(const auto &d : mDownloads)
    {
        lRet.emplace_back(d.first);
    }

    return lRet;
}

std::tuple<std::wstring,double,double,double> CBitDaemon::GetDownloadInfo(uint64_t pID)
{
    CDownload *lDownload=mDownloads.at(pID);
    return std::make_tuple(lDownload->GetName(),lDownload->GetProgress(),lDownload->GetDLSpeed(),lDownload->GetULSpeed());
}

/*namespace bitdaemon*/ } /*namespace buola*/ }

using namespace buola;

int main(int pNArgs,char **pArgs)
{
    buola_init(pNArgs,pArgs);
    bitdaemon::CBitDaemon lService;
    buola_main_loop();
    return buola_finish();
}
